import React from 'react'
import {Space, Modal, InputNumber, Input, Form, Select, Button, message} from 'antd'
import {CloseCircleOutlined, PlusOutlined} from '@ant-design/icons';
import TheTable from '@/components/TheTable'
import TheButton from '@/components/TheButton'
import TheUpload from "@/components/TheUpload";
import GoBack from '@/components/TheGoBack'
import {apiGetMhcResourceDetail, apiGetMhcResourceEdit} from "@/request/callSetting/resourceSate";
import TheImage from "@/components/TheImage";

const {Option} = Select
const formItemLayout = {
    labelCol: {
        xs: {span: 24},
        sm: {span: 4},
    },
    wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
    },
};
//参数位置
const formItemLayoutWithOutLabel = {
    wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 16, offset: 4},
    },
};

//编辑资源位设置
export default class FeedbackInfo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            mhcResourceId: props.match.params.id,
            mode: props.match.params.mode,
            resourceName: '',
            columns: [
                {
                    title: '图片',
                    dataIndex: 'resourceConfigImage',
                    key: 'resourceConfigImage',
                    render: (text) => {
                        return <TheImage src={text} width={80} height={80}/>
                    }
                },
                {
                    title: '排序',
                    dataIndex: 'resourceConfigSort',
                    key: 'resourceConfigSort'
                },
            ],
            dataSource: [],
            isAddModal: false,//新增弹窗
            fileList: [],//图片
            activeList: [],//跳转页面list
            saveLoading: false,
            modalStatus: true, // 模态窗状态 true 新增 / false 编辑
            recordIndex: 0, // 编辑行索引值
            requiredUrl: true // 跳转地址是否必填
        }
    }

    componentDidMount() {
        this.getData()
        this.getActiveList()
        message.config({maxCount: 1});
        let {mode, columns} = this.state;
        if (mode === 'edit') {
            columns.push({
                title: '操作',
                fixed: 'right',
                render: (_, record, index) => {
                    return (
                        <div>
                            <TheButton onClick={() => this.onEdit(record, index)}>编辑</TheButton>
                            <TheButton onClick={() => this.onDel(index)}>删除</TheButton>
                        </div>
                    )
                }
            })
            this.setState({
                columns
            })
        }
    }

    //获取数据
    getData = async () => {
        apiGetMhcResourceDetail(this.state.mhcResourceId).then(res => {
            if (res.code === 0) {
                let requiredUrl = true;
                if (['我的顶部轮播图','首页轮播图'].includes(res.data.resourceName)) {
                    requiredUrl = false
                }
                this.setState({
                    resourceName: res.data.resourceName,
                    dataSource: res.data.detailList ?? [],
                    requiredUrl
                })
            }
        })
    }

    // 跳转页面下拉内容
    async getActiveList() {
        await React.$post('/admin/activityLink/activityLinkList').then(res => {
            if (res.code === 0) {
                this.setState({activeList: res.data})
            }
        })
    }

    // 删除
    onDel = (index) => {
        let {dataSource} = this.state
        dataSource.splice(index, 1)
        this.setState({
            dataSource: [...dataSource]
        })
    }
    onEdit = (data, index) => {
        this.setState({
            fileList: [
                {
                    uid: -1,
                    name: "image",
                    url: data.resourceConfigImage,
                },
            ],
            isAddModal: true,
            modalStatus: false,
            recordIndex: index
        }, () => {
            let url = [];
            if (data.resourceConfigUrl){
                url = data.resourceConfigUrl.split('?');
            }
            let parameter = null
            if (url.length > 1) {
                parameter = url[1].split('&').map(item => {
                    let d = item.split('=')
                    return {
                        key: d[0],
                        value: d[1]
                    }
                })
            }
            this.formRef.setFieldsValue({
                resourceConfigImage: data.resourceConfigImage,
                resourceConfigUrl: url[0],
                resourceConfigSort: data.resourceConfigSort,
                parameter
            })
        })
    }
    //新增资源
    add = () => {
        let {dataSource} = this.state
        if (dataSource && dataSource.length === 9) {
            message.error('图片最多可以上传9张！')
        } else {
            this.setState({isAddModal: true, modalStatus: true})
        }
    }
    //确定新增或修改表格数据
    onFinish = (value) => {
        if (value.parameter && value.parameter.length > 0) {
            let arr = []
            value.parameter.map(item => {
                arr.push(`${item.key}=${item.value}`)
            })
            value.resourceConfigUrl += '?' + arr.join('&')
        }
        delete value.parameter;
        let {dataSource, modalStatus, recordIndex} = this.state
        if (modalStatus) {
            dataSource.push(value)
        } else {
            dataSource[recordIndex] = value
        }
        this.setState({
            dataSource: [...dataSource]
        })
        this.cancel();
    }
    //取消并关闭弹窗
    cancel = () => {
        this.setState({isAddModal: false, fileList: []}, () => {
            this.formRef.resetFields()
        })
    }
    //上传图片
    getFileResult = data => {
        if (data.length > 0 && data[0].hasOwnProperty('response') && data[0].response) {
            let str = data[0].response.data
            this.formRef.setFieldsValue({resourceConfigImage: str})
        } else {
            this.formRef.setFieldsValue({resourceConfigImage: ''})
        }
    }
    //确认修改资源名称内容
    submitEdd = () => {
        let {dataSource, mhcResourceId} = this.state
        this.setState({
            saveLoading: true
        })
        apiGetMhcResourceEdit({
            mhcResourceId,
            detailList: dataSource
        }).then(res => {
            if (res.code === 0) {
                message.success('保存成功')
                this.props.history.goBack()
            }
            this.setState({
                saveLoading: false
            })
        })

    }

    render() {
        const {
            columns,
            dataSource,
            isAddModal,
            fileList,
            activeList,
            resourceName,
            saveLoading,
            modalStatus,
            mode,
            requiredUrl
        } = this.state
        return (
            <div className='p-layout-box'>
                <GoBack history={this.props.history} title={"资源位详情"}/>
                <br/>
                <Space direction='vertical' style={{fontSize: 14, marginBottom: 20}}>
                    <span>资源位名称：<span>{resourceName}</span></span>
                    <span>上传图片：<span style={{color: '#aaa'}}>建议尺寸600*800，单张不超过10M</span></span>
                    {mode === 'edit' &&
                        <TheButton style={{width: 80}} size='middle' type="default" onClick={this.add}>新增</TheButton>}
                </Space>
                <TheTable columns={columns} dataSource={dataSource}/>
                {mode === 'edit' && <Space style={{margin: 'auto'}}>
                    <Button onClick={() => {
                        this.props.history.goBack()
                    }}>取消</Button>
                    <Button loading={saveLoading} onClick={this.submitEdd}>保存</Button>
                </Space>}
                <Modal
                    width='30%'
                    title={modalStatus ? "新增" : "编辑"}
                    open={isAddModal}
                    // destroyOnClose
                    footer={null}
                    onCancel={() => {
                        this.cancel()
                    }}
                >
                    <Form
                        ref={(ref) => {
                            this.formRef = ref;
                        }}
                        {...formItemLayout}
                        onFinish={this.onFinish}
                    >
                        <Form.Item name="resourceConfigImage" label="图片"
                                   rules={[{required: true, message: '请上传图片'}]}>
                            <TheUpload isConversion={false} maxSize={9} fileList={fileList} len={1}
                                       getFileResult={this.getFileResult}/>
                        </Form.Item>
                        <Form.Item name="resourceConfigSort" label="排序"
                                   rules={[{required: true, message: '请输入排序'}]}>
                            <InputNumber precision={0} min={0} max={999} placeholder='序号越小越靠前'/>
                        </Form.Item>
                        <Form.Item name='resourceConfigUrl' label={'跳转页面'}
                                   rules={[{required: requiredUrl, message: '请选择跳转页面'}]}>
                            <Select allowClear placeholder={'未选择'}>
                                {
                                    activeList.map(item => <Option value={item.activityLink}
                                                                   key={item.id}>{item.activityName}</Option>)
                                }
                            </Select>
                        </Form.Item>
                        <Form.List name="parameter">
                            {(fields, {add, remove}) => (
                                <>
                                    <Form.Item label="参数">
                                        <Button type="dashed" onClick={() => add()} block>添加参数</Button>
                                    </Form.Item>
                                    {fields.map(({key, name, ...restField}) => (
                                        <Form.Item
                                            {...formItemLayoutWithOutLabel}
                                            required={false}
                                            key={key}
                                            style={{
                                                margin: 0
                                            }}
                                        >
                                            <Space style={{display: 'flex', marginBottom: 0,}} align="baseline">
                                                <Form.Item
                                                    {...restField}
                                                    name={[name, 'key']}
                                                    rules={[{required: true, message: '请输入参数名',}]}

                                                >
                                                    <Input placeholder="参数名"/>
                                                </Form.Item>
                                                <Form.Item
                                                    {...restField}
                                                    name={[name, 'value']}
                                                    rules={[{required: true, message: '请输入参数值'}]}
                                                >
                                                    <Input placeholder="参数值"/>
                                                </Form.Item>
                                                <CloseCircleOutlined onClick={() => remove(name)}/>
                                            </Space>
                                        </Form.Item>
                                    ))}

                                </>
                            )}
                        </Form.List>
                        <Space style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                            <Button key="back" onClick={this.cancel}>取 消</Button>
                            <Button type="primary" htmlType="primary">确 定</Button>
                        </Space>
                    </Form>

                </Modal>
            </div>
        )
    }
}
